package org.example.udf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

/**
 * @ClassName MyUDF
 * @Author 小坏
 * @Date 2021/9/23、11:34
 * @Version 1.0
 */
public class MyUDF extends GenericUDF {

    /**
     * 校验数据参数个数
     *
     * @param objectInspectors
     * @return
     * @throws UDFArgumentException
     */
    @Override
    public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
        if (objectInspectors.length != 1) {
            throw new UDFArgumentException("参数个数不为1");
        }
        //返回类型是INT类型
        return PrimitiveObjectInspectorFactory.javaIntObjectInspector;
    }

    /**
     * 处理数据的方法
     *
     * @param deferredObjects
     * @return
     * @throws HiveException
     */
    @Override
    public Object evaluate(DeferredObject[] deferredObjects) throws HiveException {

        //1、取出输入数据
        String input = deferredObjects[0].get().toString();

        //防止为null
        if (input == null) {
            return 0;
        }
     //返回长度
        return input.length();
    }

    @Override
    public String getDisplayString(String[] strings) {
        return "";
    }
}
